package org.example.marker.service.impl;

import lombok.Getter;
import lombok.Setter;
import org.springframework.util.Assert;

/**
 * @author Wills
 * @date 2020/05/26
 */
@Getter
public class BitsAllocator {
    /**
     * Total 64 bits
     */
    public static final int TOTAL_BITS = 1 << 6;

    /**
     * Bits for [sign-> appId-> second-> workId-> sequence]
     */
    private final int signBits = 1;
    private final int blankBits = 11;
    private final int appBits;
    private final int timestampBits;
    private final int workerIdBits;
    private final int sequenceBits;
    @Setter
    private String epochStr;
    @Setter
    private long epochSeconds;

    /**
     * Max value for workId & sequence
     */
    private final long maxAppId;
    private final long maxDeltaSeconds;
    private final long maxWorkerId;
    private final long maxSequence;

    /**
     * Shift for timestamp & workerId
     */
    private final int appShift;
    private final int timestampShift;
    private final int workerIdShift;

    public BitsAllocator(int appBits, int timestampBits, int workerIdBits, int sequenceBits) {

        int allocateTotalBits = this.signBits + this.blankBits + appBits + timestampBits + workerIdBits + sequenceBits;
        Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits");

        // initialize bits
        this.timestampBits = timestampBits;
        this.workerIdBits = workerIdBits;
        this.sequenceBits = sequenceBits;
        this.appBits = appBits;

        // initialize max value
        this.maxAppId = ~(-1L << appBits);
        this.maxDeltaSeconds = ~(-1L << timestampBits);
        this.maxWorkerId = ~(-1L << workerIdBits);
        this.maxSequence = ~(-1L << sequenceBits);

        // initialize shift
        this.appShift = timestampBits + workerIdBits + sequenceBits;
        this.timestampShift = workerIdBits + sequenceBits;
        this.workerIdShift = sequenceBits;
    }

    public long allocate(long appId, long deltaSeconds, long workerId, long sequence) {
        return appId << this.appShift | (deltaSeconds << this.timestampShift) | (workerId << this.workerIdShift) | sequence;
    }

    public long allocateWithoutAppId(long deltaSeconds, long workerId, long sequence) {
        return (deltaSeconds << this.timestampShift) | (workerId << this.workerIdShift) | sequence;
    }

}